package com.sj.purchase.modules.cost.repository.price;

import com.sj.purchase.modules.cost.bo.CostPriceBO;
import org.springframework.beans.factory.annotation.Autowired;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by yangrd on 2017/10/27
 **/
public class CostPriceRepositoryImpl implements CostPriceRepositoryCustom {

    @Autowired
    private EntityManager entityManager;

    @Override
    public List<CostPriceBO> findCostPricePOByMaxDate() {
        Query query = entityManager.createNativeQuery(" select  a.sku_no,a.create_date, " +
                " LEFT(a.price_c,IF(LOCATE(',',a.price_c)=0,LENGTH(a.price_c),LOCATE(',',a.price_c)-1)) avg_cost_price, " +
                " LEFT(a.qty_c,IF(LOCATE(',',a.qty_c)=0,LENGTH(a.qty_c),LOCATE(',',a.qty_c)-1)) inventory_qty " +
                " FROM " +
                " (SELECT " +
                "  t_cost_price.sku_no, " +
                "  GROUP_CONCAT(t_cost_price.avg_cost_price ORDER BY t_cost_price.create_date desc) price_c,  " +
                "  max(t_cost_price.create_date) create_date, " +
                "  GROUP_CONCAT(t_cost_price.inventory_qty ORDER BY t_cost_price.create_date desc) qty_c " +
                " FROM " +
                " t_cost_price " +
                " GROUP BY t_cost_price.sku_no) a ");

        List<Object[]> result = query.getResultList();
        return result.stream().map(objects -> new CostPriceBO((String) objects[0], (Date) objects[1], Double.valueOf((String) objects[2]), Long.valueOf((String) objects[3]))).collect(Collectors.toList());
    }
}
